<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Events\Admin\AdminEvent;
use App\Http\Model\Admin\Menu;
use App\Http\Model\Admin\Role;
use App\Http\Model\Admin\RoleMenu;
use app\Providers\PhpTreeServiceProvider;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class RoleMenuController extends BaseController
{

    public function index($role_id)
    {
        $role = new Role();
        $menu = new Menu();
        $role_info = $role->findOneById($role_id);
        $role_menu = $role->findOneById($role_id)->menus;
        $related_menu = [];
        if ($role_menu) {
            foreach ($role_menu as $item) {
                array_push($related_menu, $item['id']);
            }
        }
        $menu_list = $menu->findAllValid();
        return view('admin.role_menu', [
            'role_info' => $role_info,
            'menu_list' => PhpTreeServiceProvider::makeTreeForHtml($menu_list),
            'related_menu' => $related_menu
        ]);
    }

    public function store(Request $request, $role_id)
    {
        $input = Input::all();
        $menu_ids = $input && isset($input['menu_ids']) ? $input['menu_ids'] : [];
        if ($menu_ids) {
            $obj = [];
            $new_obj = [];
            foreach ($menu_ids as $item) {
                array_push($obj, [
                    'role_id' => $role_id,
                    'menu_id' => $item
                ]);
                array_push($new_obj, $item);
            }
            //删除
            $delete_rs = (new RoleMenu())->deleteBatch($role_id);
            if ($delete_rs) {
                //添加
                $add_rs = (new RoleMenu())->createBatch($obj);
                if ($add_rs) {
                    event(new AdminEvent('set_role_menu', $new_obj, $input));
                    return redirect('admin/role');
                } else {
                    return back()->with('errors', Config::get('admin.errors.editFail'));
                }
            } else {
                return back()->with('errors', Config::get('admin.errors.editFail'));
            }
        }
        else{
            //清空权限
            $delete_rs = (new RoleMenu())->deleteBatch($role_id);
            if($delete_rs){
                event(new AdminEvent('set_role_menu', [], $input));
                return redirect('admin/role');
            }
        }
    }


}
